import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { AdminService, AutoNode } from '../services/admin.service';
import { MySelection } from 'app/modules/base/selection';
import { switchMap, map, tap } from 'rxjs/operators';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subscription } from 'rxjs';

@Component({
	selector: 'm-auth-node',
	templateUrl: './auth-node.component.html',
	styleUrls: ['./auth-node.component.scss'],
	providers: [
		{
			multi: true,
			provide: NG_VALUE_ACCESSOR,
			useExisting: AuthNodeComponent,
		},
	],
})
export class AuthNodeComponent implements OnInit, ControlValueAccessor, OnDestroy {
	constructor(private adminService: AdminService) {}
	@Input() disabled = false;

	nodes$ = this.adminService.auth_nodes().toPromise();
	nodeSelection = new MySelection<AutoNode>('id');
	nodeSelectedAll$ = this.nodeSelection.change.pipe(
		switchMap(() => this.nodes$),
		map(nodes => this.nodeSelection.isSelected(...nodes)),
	);

	nsTouchedSubscription: Subscription
	nsChangeSubscription: Subscription

	ngOnInit() {}

	allNodeChange(checked: boolean) {
		this.nodes$.then(nodes => {
			return checked ? this.nodeSelection.select(...nodes) : this.nodeSelection.unselect(...nodes);
		});
	}

	writeValue(val: number[]): void {
		if (!val) {
			return;
		}
		this.nodeSelection.select(...val.map(id => ({ id, name: '' })));
	}
	registerOnChange(fn: any): void {
		this.nsChangeSubscription = this.nodeSelection.change.pipe(map(() => this.nodeSelection.keys())).subscribe(fn);
	}
	registerOnTouched(fn: any): void {
		this.nsTouchedSubscription = this.nodeSelection.change.subscribe(fn);
	}
	setDisabledState?(isDisabled: boolean): void {
		this.disabled = isDisabled;
	}

	ngOnDestroy(): void {
		this.nsChangeSubscription.unsubscribe();
		this.nsTouchedSubscription.unsubscribe();
	}

}
